import socket
import time

from absl import app, flags

from coin.exchange.kr_rest.feed.feed_impl import generate_feed_subscriber
from coin.exchange.util.simple_record import RecordWriter

FLAGS = flags.FLAGS

flags.DEFINE_string('exchange', None, 'exchange name')
flags.DEFINE_string('api_version', None, 'api_version')
flags.DEFINE_string('product', None, 'product')
flags.DEFINE_string('filename', None, 'filename')
flags.DEFINE_bool('verbose', None, 'verbose')


def main(_):
  feed = generate_feed_subscriber("Spot", FLAGS.exchange, FLAGS.api_version, FLAGS.product)

  if FLAGS.filename is not None:
    filename = FLAGS.filename
  else:
    filename = "data/%s.%s.%s.%s.%d" % (
        FLAGS.exchange, FLAGS.api_version, feed.product, socket.gethostname(), int(time.time()))

  print("saving to " + filename)

  writer = RecordWriter(filename)
  while (True):
    try:
      feed.query_book()
      if feed.is_price_float:
        pb = feed.get_proto_feed_float()
      else:
        pb = feed.get_proto_feed()
      writer.write_record(pb.SerializeToString())
      writer.flush()
      if FLAGS.verbose:
        print(pb)
    except Exception as e:
      print("exception", e)


if __name__ == '__main__':
  app.run(main)
